package com.own.business.system.user.business.method;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.own.business.system.account.common.hook.AccountLogoutHook;
import com.own.business.system.user.entity.po.SystemUser;
import com.own.business.system.user.entity.po.SystemUserInfo;
import com.own.business.system.user.entity.po.SystemUserSecurity;
import com.own.business.system.user.mapper.SystemUserInfoMapper;
import com.own.business.system.user.mapper.SystemUserMapper;
import com.own.business.system.user.mapper.SystemUserSecurityMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * SystemUserAccountLogoutMethodHookImpl
 *
 * @author chenxueli
 * @date 2023-08-09 15:33:00
 */
@Slf4j
@Component
public class SystemUserAccountLogoutMethodHookImpl implements AccountLogoutHook {

    @Resource
    private SystemUserMapper systemUserMapper;
    @Resource
    private SystemUserInfoMapper systemUserInfoMapper;
    @Resource
    private SystemUserSecurityMapper systemUserSecurityMapper;

    /**
     * 执行
     *
     * @param userId 用户id
     * @param reason 注销原因
     */
    @Override
    public void run(Long userId, String reason) {
        // 删除账号信息
        {
            if (StringUtils.isNotBlank(reason)) {
                var wrapper = new LambdaUpdateWrapper<SystemUser>().eq(SystemUser::getId, userId).set(SystemUser::getMemo, reason);
                systemUserMapper.update(null, wrapper);
            }
            var wrapper = new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getId, userId);
            systemUserMapper.delete(wrapper);
        }
        // 删除用户信息
        {
            var wrapper = new LambdaQueryWrapper<SystemUserInfo>().eq(SystemUserInfo::getFkUserId, userId);
            systemUserInfoMapper.delete(wrapper);
        }
        // 删除用户安全信息
        {
            var wrapper = new LambdaQueryWrapper<SystemUserSecurity>().eq(SystemUserSecurity::getFkUserId, userId);
            systemUserSecurityMapper.delete(wrapper);
        }
    }
}
